package com.learn.shop.filter;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "sessionFilter", urlPatterns = "/**")
@Slf4j
public class SessionFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);
        String requestURI = req.getRequestURI();

        logger.info("requestURI->{}" + requestURI);

        String username = (String) req.getSession().getAttribute("username");
        if (requestURI.contains("/index")
                || requestURI.contains("/js/**")
                || requestURI.contains("/img/**")
                || requestURI.contains("/css/**")
                || requestURI.contains("/plugins/**")) {
            chain.doFilter(request, response);
        } else {
            if (username != null && session != null) {
                chain.doFilter(request, response);
            } else {
                res.sendRedirect("index");
            }
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("过滤器Filter------>init...执行");
    }

    @Override
    public void destroy() {
    }
}


